/*
 * Copyright (c) 2015. For Intelligent Group.
 */

package com.intelligent.ispc.web.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import javax.servlet.ServletRequest;

/**
 * Created by cherry on 2016/2/2.
 */
public final class PageUtil {

    public static PageRequest buildPageWithParameters(ServletRequest request, int pageSize) {
        return PageUtil.buildPageWithParameters(request, pageSize, null, null);
    }

    public static PageRequest buildPageWithParameters(ServletRequest request, int pageSize, String sortStr) {
        return PageUtil.buildPageWithParameters(request, pageSize, sortStr, null);
    }

    public static PageRequest buildPageWithParameters(ServletRequest request, int pageSize, String sortStr, Sort.Direction sortDirection) {
        Integer start = 0;
        Integer draw = 0;
        if (StringUtils.isNotBlank(request.getParameter("start"))) {
            start = Integer.valueOf(request.getParameter("start"));
        }
        Integer size = pageSize;
        if (StringUtils.isNotBlank(request.getParameter("length"))) {
            size = Integer.valueOf(request.getParameter("length"));
        }

        if (StringUtils.isNotBlank(request.getParameter("draw"))) {
            draw = Integer.valueOf(request.getParameter("draw"));
        }

        Integer pageNum = 0;
        if ((start / size) > 0) {
            pageNum = start / size;
        }

        Sort sort = null;
        if (StringUtils.isNotBlank(sortStr)) {
            if (sortDirection != null) {
                sort = new Sort(sortDirection, sortStr);
            } else {
                sort = new Sort(Sort.Direction.ASC, sortStr);
            }
        }

        return new PageRequest(pageNum, size, sort);
    }
}
